package com.ls.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import java.io.*;
import java.util.Collection;

/**
 * <p></p>
 * Created by zhezhiyong@163.com on 2017/3/1.
 */
public class SessionRedisDao extends AbstractSessionDAO {
    // 创建session，保存到数据库
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        RedisDb.setObject(sessionId.toString().getBytes(), sessionToByte(session));
        return sessionId;
    }

    // 获取session
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = null;
        // 先从缓存中获取session，如果没有再去数据库中获取
        byte[] bytes = RedisDb.getObject(sessionId.toString().getBytes());
        if (bytes != null && bytes.length > 0) {
            session = byteToSession(bytes);
        }
        return session;
    }

    // 把session对象转化为byte保存到redis中
    public byte[] sessionToByte(Session session) {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        byte[] bytes = null;
        try {
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(session);
            bytes = bo.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    // 把byte还原为session
    public Session byteToSession(byte[] bytes) {
        ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
        ObjectInputStream in;
        SimpleSession session = null;
        try {
            in = new ObjectInputStream(bi);
            session = (SimpleSession) in.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return session;
    }

    // 更新session的最后一次访问时间
    @Override
    public void update(Session session) throws UnknownSessionException {
        RedisDb.setObject(session.getId().toString().getBytes(), sessionToByte(session));
    }
    // 删除session
    @Override
    public void delete(Session session) {
        RedisDb.delString(session.getId() + "");
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return null;
    }
}
